#pragma once
#include  <iostream>
#include  <memory>
#include  <QDebug>
#include <QImage>
#include "Data/CircularBuffer.h"
#include "Data/FileInfo.h"
#include "Media/Decoder/BaseDecoder.h"
#include "Data/CircularBuffer.h"
extern "C" {
#include <libswscale/swscale.h>
}
class OptimizationContext {
public:
    // Constructor
    OptimizationContext(CircularBuffer<AVFrame>& input_queue) : m_queue(input_queue),m_type(""),m_outputSize(0, 0) {}

    // Get the queue
    CircularBuffer<AVFrame>& getQueue() {
        return m_queue;
    }
    // Get the type
    const std::string& getType() const {
        return m_type;
    }
    //output to map
    void outputToMap(std::map<int, QImage>& map) {
        // 实现双缓冲策略
    }
    QImage frameToQImage(const AVFrame* frame, bool saveImage = false) {
        int width = frame->width;
        int height = frame->height;
        QImage img(width, height, QImage::Format_RGB32);
        SwsContext* sws_ctx = sws_getContext(width, height, static_cast<AVPixelFormat>(frame->format), width, height, AV_PIX_FMT_RGB32, SWS_BILINEAR, nullptr, nullptr, nullptr);
        
        if (!sws_ctx) {
            // Error handling: sws_getContext failed
            std::cout << "sws_getContext failed" << std::endl;
            return QImage();
        }
        
        uint8_t* data[1] = { reinterpret_cast<uint8_t*>(img.bits()) };
        int linesize[1] = { static_cast<int>(img.bytesPerLine()) };
        int ret = sws_scale(sws_ctx, frame->data, frame->linesize, 0, height, data, linesize);
        
        sws_freeContext(sws_ctx);
        
        if (ret != height) {
            // Error handling: sws_scale failed
            std::cout << "sws_scale failed" << std::endl;
            return QImage();
        }

        // Optionally save the output image to a file
        if (saveImage) {
            // Construct the filename with the frame's PTS
            QString filename = QString("output_%1.png").arg(frame->pts);
            if(m_outputSize.first == 0 || m_outputSize.second == 0) {
                img.save(filename);
            } else {
                QImage scaledImg = img.scaled(m_outputSize.first, m_outputSize.second);
                scaledImg.save(filename);
            }
        }

        return img;
    }
    void setOutputImageSize(int width, int height) {
        m_outputSize = std::make_pair(width, height);
        std::cout << "Set output image size to " << width << "x" << height << std::endl;
    }


private:
    CircularBuffer<AVFrame>& m_queue;  // Reference to the queue
    std::string m_type;  // The type of the data
    std::pair<int, int> m_outputSize;  // The output size
};
